package com.briup.pts.util;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.UUID;

public class UploadUtil {

    private static final String accessKey = "R1sMWPmXyHjnfyeZug0XKbBmBNCJwwrtPzlS2DSE";
    private static final String secretKey = "8ej0vvUAofJszVJuh9zoFFR7rnn5l28grhP724MR";
    private static final String bucketName = "iknow-test181";
    private static final String baseUrl = "http://snamekdeo.hn-bkt.clouddn.com/";

    /**
     * 将数据传输到OSS对象存储服务中
     *
     * @param file MultipartFile 类型的文件
     * @return 返回文件的URL链接
     */
    public static String uploadToOss(MultipartFile file) {
        //构造一个 自动选择区域的 配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        // 创建文件上传 管理器
        UploadManager uploadManager = new UploadManager(cfg);

        // 根据ak和sk 以及 bucketName获取上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(bucketName);

        String fileName = generatorFileName(file);

        // 上传数据，指定文件在OSS服务中的名称
        try {
            uploadManager.put(file.getInputStream(), fileName,
                    uploadToken, null, null);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败，请重新上传");
        }
        // 返回URL路径
        return baseUrl + fileName;
    }
    private static String generatorFileName(MultipartFile file) {
        // a.txt.jpg.txt
        String[] infos = file.getName().split("[.]");
        // 获取文件的后缀
        String suffix = infos[infos.length - 1];
        String date = LocalDate.now().toString();
        String name = UUID.randomUUID()
                .toString().replace("-", "");

        return String.format("%s/%s.%s", date, name, suffix);
    }
}
